package lnkwe.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * Created by lijing on 2016-03-24.
 */
public class DateUtil {
    private static final String DEFAULT_PATTERN = "yyyy-MM-dd HH:mm:ss";

    //字符转换日期格式
    public static Date convertStringToDate(String strDate, String pattern) {
        if (StringUtil.isNull(strDate))
            return null;
        if (StringUtil.isNull(pattern))
            pattern = DEFAULT_PATTERN;
        SimpleDateFormat df = new SimpleDateFormat(pattern);
        try {
            return df.parse(strDate);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

    //日期格式化
    public static String convertDateToString(Date aDate, String pattern) {
        if (aDate == null)
            return null;
        if (StringUtil.isNull(pattern))
            pattern = DEFAULT_PATTERN;
        SimpleDateFormat df = new SimpleDateFormat(pattern);
        return df.format(aDate);
    }


    /*获取日期与当前时间的相隔天数
    *@param date 日期与当前时间比较
    * */
    public static long getDays(Date date) {
        Calendar nowCal=Calendar.getInstance();
        nowCal.setTime(new Date());

        Calendar dateCal=Calendar.getInstance();
        dateCal.setTime(date);
        long nowTime=nowCal.getTimeInMillis();
        long dateTime=dateCal.getTimeInMillis();
        long time=(dateTime-nowTime)/(1000*3600*24);
        return time;
    }

    public static long getDateTimeNumber(Date d, Date t) {
        Calendar c1 = Calendar.getInstance();
        c1.setTime(d);
        Calendar c2 = Calendar.getInstance();
        c2.setTime(t);
        c1.set(Calendar.HOUR_OF_DAY, c2.get(Calendar.HOUR_OF_DAY));
        c1.set(Calendar.MINUTE, c2.get(Calendar.MINUTE));
        c1.set(Calendar.SECOND, c2.get(Calendar.SECOND));
        c1.set(Calendar.MILLISECOND, c2.get(Calendar.MILLISECOND));
        return c1.getTimeInMillis();
    }
    public static Date getExpireDate(int time){
        Date now = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(now);

        calendar.add(Calendar.SECOND,time);
        Date expireDate = calendar.getTime();
        return calendar.getTime();
    }

}
